#! /usr/local/bin/perl5

use strict;
use warnings ( FATAL => 'all' );

# use lib "../perllib";

use Data::Dumper;
use File::Basename;
use Readonly;
use POSIX qw(strftime);

use FixInc::Logger;
use FixInc::DBAccess;
use FixInc::OopOptsDB;
use Feeds::API::File;
use DateTime;

use constant SCRIPT_NM => basename($0);

Readonly my $HOST_NM => $ENV{HOST} || `hostname | tr -d '\n'`;
Readonly my $NOW => strftime( '%Y%m%d.%H%M%S', localtime );
Readonly my $TODAY => $ENV{TODAY_CYMD} || substr( $NOW, 0, 8 );

print "host_nm is:\[", $HOST_NM, "\]\n";
print "NOW     is:\[", $NOW,     "\]\n";
print "TODAY   is:\[", $TODAY,   "\]\n";

# Turn on output autoflush
$| = 1;

# setup log object
my $l = FixInc::Logger->new( min_level => 'notice' );
my $script_nm = SCRIPT_NM;
$l->notice("=== $script_nm has started === (pid=$$) (ppid=@{[getppid()]})");
$l->info( "CMD:", $0, join( " ", @ARGV ) );

for my $argvv ( @ARGV ) {
	print "argvvvvvvvv is \[", $argvv, "\]\n";
}

## Parse Jobparams ##
my $defs = FixInc::OopOptsDB->newOptSet(
    help => <<'EOH',
This script downloads xml data from oekb web site https://www.profitweb.at
EOH

    defaults => {
        server          => 'HGCDB1',
        web_usr         => 'wdbo_reuters',
        web_retry       => '3',
        delete_fail     => 'y',
        download_days   => '7',
        date_mode       => '1',
        download_mode   => 'D',          ##I=> initial load(both include code tables and none-code tables
    },                                   ##C=> Get code tables' data
                                         ##D=> Get daily update data
                                         ##T=> Get the text data
                                         ##M=> make up the wrong daily updates
                                         
    optdefs => FixInc::OopOptsDB->newOptDef(
        {   name     => 'web_usr',
            aliases  => ['WS'],
            maxargs  => 1,
            required => 1,
            type     => 'string',
            help     => 'The username of HTTPS login.'
        },
        {   name     => 'web_pass',
            aliases  => ['WP'],
            maxargs  => 1,
            required => 1,
            type     => 'string',
            help     => 'The password of the web login user.'
        },
        {   name     => 'web_proxy',
            aliases  => ['WPR'],
            maxargs  => 1,
            required => 0,
            type     => 'string',
            help     => 'The password of the web login user.'
        },
        {   name     => 'web_retry',
            aliases  => ['WR'],
            maxargs  => 1,
            required => 0,
            type     => 'string',
            help     => 'The curl retry times when it encounters errors.'
        },
        {   name     => 'tbl_url',
            aliases  => ['TU'],
            required => 1,
            maxargs  => 1,
            type     => 'string',
            help     => 'The URL of download an Oekb table data.'
        },
        {   name     => 'daily_up_url',
            aliases  => ['DUU'],
            required => 1,
            maxargs  => 1,
            type     => 'string',
            help     => 'The URL of download Oekb daily update data.'
        },
        {   name     => 'email_success',
            aliases  => ['ES'],
            required => 0,
            maxargs  => 9,
            type     => 'string',
            help     => 'email address'
        },
        {   name     => 'email_failure',
            aliases  => ['EF'],
            required => 0,
            maxargs  => 9,
            type     => 'string',
            help     => 'email address'
        },
        {   name     => 'download_mode',
            aliases  => ['DM'],
            required => 1,
            maxargs  => 1,
            type     => 'string',
            help     => 'The download mode: I,C,D.'
        },
        {   name     => 'delete_fail',
            aliases  => ['DF'],
            required => 0,
            maxargs  => 1,
            type     => 'string',
            help     => 'If delete downloaded files when failure'
        },
        {   name     => 'holidays',
            aliases  => ['HO'],
            required => 0,
            maxargs  => 30,
            type     => 'string',
            help     => 'The holidays that do not need to download data from website'
        },
        {   name     => 'download_days',
            aliases  => ['DD'],
            required => 1,
            maxargs  => 1,
            type     => 'string',
            help     => 'How many days data are needed.'
        },
        {   name     => 'date_mode',
            aliases  => ['DAM'],
            required => 1,
            maxargs  => 1,
            type     => 'string',
            help     => 'Use datum or log_datum to download daily updates'
        },
    )
);

my $log = FixInc::Logger->new( min_level => 'info' );

my $oops = FixInc::OopOptsDB->new(
    'optset' => $defs,
    'log'    => $log
    )
    or $l->die("Cannot process options: FixInc::OopOptsDB->new");



my $O = $oops->opthash;
$log->paramApply($O);


# create database handlers
# 2) feed

print "oops---opthash=\[",%$O, "]\n";
print "ooooooooo=\[", $O, "]\n";
print "startxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n";
my $prog = $defs->name();
my $args1 = $O->{$prog};
foreach my $opt_key (sort keys %$O ) {
	#next if $opt_key = $prog;
	$log->info("Option $opt_key => $O->{$opt_key}");
}
if ($args1) {
	if (ref $args1) {
		print "11ififififififif\n";		
		$log->info("Arguments => @$args1");
	}
	else {
		print "elseelseelseelse\n";
		$log->info("Arguments => $args1");
	}
}
print "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n";

#print "web_usr=\[", $web_usr, "\]\n";
#print "web_pass=\[", $web_pass, "\]\n";

$log->info("Create $O->{database} db handler ...");
my $feed_dbh = Feeds::API::FeedDB->paramApply($O)->connect( %$O, log => $log )
    or $log->die( "'$script_nm': Cannot connect to '$O->{server}': ",
        $FixInc::DBAccess::errstr );

# get CFA database version
my $fdb_version = Feeds::API::FeedDB->feeddb_version(%$O);

print "feed_dbhfeed_dbh=\[", $feed_dbh, "\]\n";
print "fdb_version     =\[", $fdb_version, "\]\n";

# register job info
my $job = Feeds::API::Job->new( action_type => "oekb_xml_download", log => $log)
    or $log->die("Cannot create new Feeds::API::Job: $!");

print "oooooooooooooooooooooooooooooooo\n";
$log->info(localtime);
$log->info(time);
my $query_sql = "select top 1000 party_id from dmo_govcorp..party";
my $prows = $feed_dbh->selectall_hashes($query_sql);
my $count=0;

foreach my $ret (@$prows)
{
	$query_sql = "select cur_immed_parent_id from dmo_govcorp..party where party_id = '$ret'";
    my $prows1 = $feed_dbh->selectall_hashes($query_sql);
}

$log->info(localtime);
$log->info(time);
print "ooooooooooooooooooooooooooooooooo\n";

print "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\n";
$log->info(localtime);
$log->info(time);
my $query_sql2 = "select distinct(cur_ultimate_parent_id) from dmo_govcorp..party";
my $prows2 = $feed_dbh->selectall_hashes($query_sql2);
my $max_no = 0;

foreach my $ret2 (@$prows2)
{
	my $cur_ultimate_parent_id = $ret2->{cur_ultimate_parent_id};
	if ($cur_ultimate_parent_id) {
	} else {
		$cur_ultimate_parent_id = 'null'
	}
	$query_sql2 = "select count(*) as no from dmo_govcorp..party where cur_ultimate_parent_id = $cur_ultimate_parent_id";
    my $prows3 = $feed_dbh->selectall_hashes($query_sql2);
    
    foreach my $ret3 (@$prows3)
    {
    	if ($cur_ultimate_parent_id != 'null') {
	    	if ($ret3->{no}) {
	    		$max_no = $ret3->{no};
	    	}
    	}
    	$log->info("No $cur_ultimate_parent_id: The count is $ret3->{no}\n");
    }
}

$log->info("the max_no: The max_no is $max_no\n");
$log->info(localtime);
$log->info(time);
print "qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\n";

$job->success();

# to force DESTROY
undef $job;
$feed_dbh->disconnect() if defined $feed_dbh;
$log->notice("=== @{[SCRIPT_NM]} has stopped ===");

__END__
